#!/usr/bin/env php
<?php
include_once(dirname(__FILE__).'/config.php');
include_once(dirname(__FILE__).'/utilities.php');

$store = ARC2::getStore($arc_config);

$time = time();

$q = <<<EOT
PREFIX vocabs: <http://desanti.org/schemas/vocabularies#>
SELECT * WHERE {
    ?v a vocabs:Vocabulary .
    ?v vocabs:hasRelation ?r .
}
EOT;
$rs = $store->query($q);
if(!$store->getErrors()){
	$rows = $rs['result']['rows'];
    foreach($rows as $row){
        $time += 1;
        $newR = 'http://desanti.org/relations/'.$time;
        $r = label($row,'r');
        $q = <<<EOT
PREFIX vocabs: <http://desanti.org/schemas/vocabularies#>
INSERT INTO <http://desanti.org/> {
    <$newR> a vocabs:Relation .
}
EOT;
        query($q, $store);
        $q = <<<EOT
SELECT * WHERE {
    $r ?p ?o .
}
EOT;
        $rs = $store->query($q);
        if(!$store->getErrors()){
            $rows = $rs['result']['rows'];
            foreach($rows as $row){
                $p = label($row,'p');
                $o = label($row,'o');
                $q = <<<EOT
DELETE {
    $r $p $o .
}
EOT;
                query($q, $store);
                $q = <<<EOT
INSERT INTO <http://desanti.org/> {
    <$newR> $p $o .
}
EOT;
                query($q, $store);
            }
        }
        $q = <<<EOT
SELECT * WHERE {
    ?s $r ?o .
}
EOT;
        $rs = $store->query($q);
        if(!$store->getErrors()){
            $rows = $rs['result']['rows'];
            foreach($rows as $row){
                $s = label($row,'s');
                $o = label($row,'o');
                $q = <<<EOT
DELETE {
    $s $r $o .
}
EOT;
                query($q, $store);
                $q = <<<EOT
INSERT INTO <http://desanti.org/> {
    $s <$newR> $o .
}
EOT;
                query($q, $store);
            }
        }
        $q = <<<EOT
SELECT * WHERE {
    ?s ?p $r .
}
EOT;
        $rs = $store->query($q);
        if(!$store->getErrors()){
            $rows = $rs['result']['rows'];
            foreach($rows as $row){
                $s = label($row,'s');
                $p = label($row,'p');
                $q = <<<EOT
DELETE {
    $s $p $r .
}
EOT;
                query($q, $store);
                $q = <<<EOT
INSERT INTO <http://desanti.org/> {
    $s $p <$newR> .
}
EOT;
                query($q, $store);
            }
        }
    }
}

?>
